<?php

namespace VisitorPattern;

// 1. 定义访问者接口、抽象文档接口、不同的文档实例，通过参数接收不同类型的文档
interface DocumentVisitor
{
    public function visitWordDocument(WordDocument $document): string;
    public function visitPdfDocument(PdfDocument $document): string;
    public function visitExcelDocument(ExcelDocument $document): string;
}

interface Document
{
    public function accept(DocumentVisitor $visitor): string;
}

class WordDocument implements Document
{
    private string $content;

    public function __construct(string $content)
    {
        $this->content = $content;
    }

    public function getContent(): string
    {
        return $this->content;
    }

    public function accept(DocumentVisitor $visitor): string
    {
        return $visitor->visitWordDocument($this);
    }
}

class PdfDocument implements Document
{
    private string $content;

    public function __construct(string $content)
    {
        $this->content = $content;
    }

    public function getContent(): string
    {
        return $this->content;
    }

    public function accept(DocumentVisitor $visitor): string
    {
        return $visitor->visitPdfDocument($this);
    }
}

class ExcelDocument implements Document
{
    private array $content;

    public function __construct(array $content)
    {
        $this->content = $content;
    }

    public function getContent(): array
    {
        return $this->content;
    }

    public function accept(DocumentVisitor $visitor): string
    {
        return $visitor->visitExcelDocument($this);
    }
}

// 2. 定义访问者，实现DocumentVisitor接口
class HtmlConverterVisitor implements DocumentVisitor
{
    public function visitWordDocument(WordDocument $document): string
    {
        return "将Word文档转化为Html格式：" . $document->getContent() . "\n";
    }

    public function visitPdfDocument(PdfDocument $document): string
    {
        return "将Pdf文档转化为Html格式：" . $document->getContent() . "\n";
    }

    public function visitExcelDocument(ExcelDocument $document): string
    {
        return "将Excel文档转化为Html格式：" . json_encode($document->getContent()) . "\n";
    }
}

// 测试
// 实例化各种文档
$word = new WordDocument("这是一个Word文档");
$pdf = new PdfDocument("这是一个Pdf文档");
$excel = new ExcelDocument([1, 2, 3, 4, 5]);

// 使用访问者进行转换
$visitor = new HtmlConverterVisitor();

echo $visitor->visitWordDocument($word);
echo $visitor->visitPdfDocument($pdf);
echo $visitor->visitExcelDocument($excel);
